package org.tigr.htc.server;

/*
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.

This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.

You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

import java.io.PrintWriter;
import java.io.File;
import java.util.Iterator;
import java.util.Date;
import org.apache.log4j.Logger;
import org.tigr.htc.cmd.*;
import org.tigr.htc.common.*;

/**
 * The <b>SSHRunner</b> class used for testing or very short commands
 * logs into the given machine and launches the command
 * currently not that useful because it launches the commands as the
 * the default user.
 */
public class SSHRunner implements IRunner {
    static Logger log = Logger.getLogger(SSHRunner.class);
    private Command cmd;
    private static final String DEFAULT_HOST = "localhost";
    final static String PASS = HTCConfig.getProperty("passwd");

    /**
     * <code>SSHRunner</code> returns a new SSHRunner
     *
     * @param cmd a <code>String</code> value
     * @param cwd
     */
    public SSHRunner(Command cmd, File cwd) {
    	log.debug("SSHRunner construct using work dir " + cwd);
    	this.cmd = cmd;
    }

    public void run() {
    	PrintWriter pw = null;
    	String host = DEFAULT_HOST;
    	StringBuffer cmdline = new StringBuffer();
    	
    	try {
    		log.debug("In run.");
    		cmd.taskSubmitted(cmd.getSubmitURL(), " no log");
    		
    		CommandConfig config = cmd.getConfig();
    		if(config.getHosts() != null) host = config.getHosts();
    		cmdline.append(cmd.getCommand() + " ");
    		
    		if(cmd.getParamsCount() > 0) {
    			Iterator params = cmd.getParams().iterator();
    			for( ; params.hasNext(); ) {
    				Param param = (Param) params.next();
    				
    				if(param.getKey() != null) {
    					cmdline.append(param.getKey().replaceAll("\\$\\(Index\\)", "0") + "=");
    				}
    				
    				if(param.getType() == ParamType.PARAM) {
    					cmdline.append(param.getValue().replaceAll("\\$\\(Index\\)", "0") + " ");
    				} 
    				else {
    					log.warn("Illegal/unknown parameter type for command type ssh.");
    				}
    			}
    		}
    		
    		if((cmd.getOutput() != null) && (!cmd.getOutput().equals(""))) {
    			cmdline.append(" > " + cmd.getOutput());
    		}
    		
    		if((cmd.getError() != null) && (!cmd.getError().equals(""))) {
    			cmdline.append(" 2> " + cmd.getError());
    		}
    		
    		log.info("cmdline is " + cmdline);
    		
    		SSHCommand sshCmd = new SSHCommand(host, PASS);
    		cmd.taskStarted("ssh cmd started", new Date(), host, 0, 0);
    		int result = sshCmd.runCommand(cmdline.toString());
    		log.debug("stdout from cmd " + cmd.getID() + " - " + sshCmd.getOutput());
    		cmd.taskFinished("ssh cmd finished with " + result, new Date(), result, 0);
    	} catch(Exception e) {
    		log.warn("Error: " + e.getMessage(), e);
    	}    	
    }

    /* (non-Javadoc)
     * @see org.tigr.htc.server.IRunner#getICommand()
     */
    public ICommand getICommand() {
    	return cmd;
    }
    
    /**
     * @return
     */
    public String getEventLog() {
    	return "no log";
    }
    
    /* (non-Javadoc)
     * @see org.tigr.htc.server.IRunner#stop()
     */
    public boolean stop() throws Exception {
    	return true;
    }
    
    /* (non-Javadoc)
     * @see org.tigr.htc.server.IRunner#hold()
     */
    public boolean hold() throws Exception {
    	return true;
    }
    
    /* (non-Javadoc)
     * @see org.tigr.htc.server.IRunner#release()
     */
    public boolean release() throws Exception {
    	return true;
    }
    
    /* (non-Javadoc)
     * @see org.tigr.htc.server.IRunner#isRunnerComplete()
     */
    public boolean isRunnerComplete() {
    	return false;
    }
}

